import sys
import time
import traceback

from lxml import etree

from cache.redis_util import getConnection
from dbse.mysql.db_entity_stock_ths_gn_current_info_daily import StockCurrentThsGnInfoDaily
from dbse.mysql.db_mysql_insert import getDataBase
from sel.proxy.selenium_proxy_util import initSelWireChromePlus, initSelWireChrome
from dbse.mysql.db_mysql_insert import addStockThsGnCurrentInfo
from date.dateUtil import getDateTime,getDate
from utils.DateUtil import isStockOpen, getNowTime, isOpenToday
import static.globals as sg
# 遍历所有概念
from utils.StockUtil import appSuspend


def handlePage(url,browser,gnCode,db):
    browser.get(url)
    # 等待元素加载完毕
    # wait.until(EC.presence_of_element_located((By.CLASS_NAME,'board-infos')))
    # time.sleep(1)

    content = browser.page_source
    html = etree.fromstring(content,etree.HTMLParser())
    result = html.xpath('//div[@class="board-infos"]//dl//dd')
    main = html.xpath('//div[@class="board-hq"]')
    price_current = main[0].getchildren()[1].text
    gn_name= main[0].getchildren()[0].text
    add_sql = 'INSERT INTO stock_ths_gn_current_info_daily (`gn_code`, `gn_name`, `price_begin`, `price_yesterday`, `price_end`, `price_max`, `price_min`, `price_increase_rate`, `rank`, `up_num`, `down_num`, `fund_input`, `amount`, `trunover`, `sta_datetime`, `price_current`) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)'
    # todo date从redis获取
    profile = sg.profile
    redis = getConnection(profile)
    staDate = redis.get("stock:sta:date")

    # 保存数据
    entity = StockCurrentThsGnInfoDaily(gnCode,
                                   gn_name,                                            #gn_name
                                   result[0].text,                                  #price_begin
                                   result[1].text,                                  #price_yesterday
                                   price_current,                                   #price_end
                                   result[3].text,                                  #price_max
                                   result[2].text,                                  #price_min
                                   None,                                            #price_increase_rate
                                   result[6].text.split("/")[0],                    #rank
                                   result[7].getchildren()[0].text,                 #up_num
                                   result[7].getchildren()[1].text,                 #down_num
                                   result[8].text,                                  #fund_input
                                   result[9].text,                                  #amount
                                   result[4].text,                                  #trunover
                                   #getDate(),                                   #sta_datetime
                                   staDate,
                                   price_current                                    # price_current
                                   )
    addStockThsGnCurrentInfo(db,add_sql,entity)
    print(entity)


def startWork(profile):
    browser = None
    redis = None
    db = None
    try:
        print(f'====task begin:{getNowTime()}====')

        # 初始化库
        db = getDataBase(profile)

        # getproxy进行了优化 将proxy进行缓存 如果在3分钟内重连 优先从缓存中拿proxy
        browser = initSelWireChrome(useProxy=False,isHeadless=False,host='https://q.10jqka.com.cn',setTimeOut=False,ignorePic=True,redis=None)

        # 查询所有概念
        # query_sql = "select distinct gn_code,gn_name,gn_url from stock_ths_gn"
        redis = getConnection(profile)
        today = redis.get("stock:sta:date").decode('utf-8')
        query_sql = f'select distinct gn_code,gn_name,gn_url from stock_ths_gn t1 where  not exists (select 1 from stock_ths_gn_current_info_daily t2 where t1.gn_code = t2.gn_code and t2.sta_datetime = {today})'
        db = getDataBase(profile)
        cursor = db.cursor()
        cursor.execute(query_sql)
        gns = cursor.fetchall()
        for gn in gns:
            gnCode = gn[0]
            url = gn[2]
            # 抓取网页
            handlePage(url=url,browser=browser,gnCode=gnCode,db=db)


        print(f'====task end:{getNowTime()}====')
    except Exception as e:
        print(f"异常信息: {e}")
        print("详细堆栈信息:")
        traceback.print_exc()  # 打印完整的堆栈跟踪
        print(f'====task exception:{getNowTime()}====')
        if browser != None:
            browser.quit()
        if db != None:
            db.close()
        if redis != None:
            redis.close()

        time.sleep(2)
        print(f'====exception occur sys quit====')
        # sys.exit()
        ## 重启任务
        startWork(profile)

profile = sys.argv[1:][0]
## 设置全局变量
sg.profile = profile
if isOpenToday():
    startWork(profile)
